package com.ruoyi.system.core.conf;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.concurrent.TimeUnit;


@Configuration
public class ElasticSearchConfig {

    private static final Logger LOGGER = LoggerFactory.getLogger(ElasticSearchConfig.class);

    private RestClientBuilder builder;

    private RestHighLevelClient client;

    private String schema = "http";

    private int maxConnectNum = 100;

    private int maxConnectPerRoute = 100;

    private int connectTimeOut = 5 * 60 * 1000;

    private int socketTimeOut = 60 * 1000;

    private int connectionRequestTimeOut = 500;

    private int KeepAliveStrategyTime=10;

    private HttpHost httpHost;

    private boolean uniqueConnectTimeConfig = true;

    private boolean uniqueConnectNumConfig = true;


    @Value("${es.host}")
    private String host;

    @Value("${es.port}")
    private int port;

    /**
     * Bean name default  函数名字
     *
     * @return
     */
    @Bean(autowire = Autowire.BY_NAME, name = "restHighLevelClient")
    public RestHighLevelClient restHighLevelClient() {
        LOGGER.info("Elasticsearch初始化开始。。。。。");
        httpHost= new HttpHost(host, port, schema);
        builder = RestClient.builder(httpHost);
        if (uniqueConnectTimeConfig) {
            setConnectTimeOutConfig();
        }
        if (uniqueConnectNumConfig) {
            setMutiConnectConfig();
        }
        try {
            // 配置信息
            client = new RestHighLevelClient(builder);
        } catch (Exception e) {
            LOGGER.error("elasticsearch RestHighLevelClient create error!!", e);
        }
        return client;
    }

    /**
     * 异步httpclient的连接延时配置
     */
    public void setConnectTimeOutConfig() {
        builder.setRequestConfigCallback(requestConfigBuilder -> {
            requestConfigBuilder.setConnectTimeout(connectTimeOut);
            requestConfigBuilder.setSocketTimeout(socketTimeOut);
            requestConfigBuilder.setConnectionRequestTimeout(connectionRequestTimeOut);
            return requestConfigBuilder;
        });
    }


    /**
     * 异步httpclient的连接数配置
     */
    public void setMutiConnectConfig() {
        builder.setHttpClientConfigCallback(httpClientBuilder -> {
            httpClientBuilder.setKeepAliveStrategy((response, context) -> TimeUnit.MINUTES.toMillis(KeepAliveStrategyTime));
            httpClientBuilder.setMaxConnTotal(maxConnectNum);
            httpClientBuilder.setMaxConnPerRoute(maxConnectPerRoute);
            return httpClientBuilder;
        });
    }

    /**
     * 关闭连接
     */
    public void close() {
        if (client != null) {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

